<template>
  <view class="waterfall">
    <view v-for="(item, index) in columnData" :key="index" class="column" :style="{ width: columnWidth + 'px' }">
      <view v-for="(childItem, childIndex) in item" :key="childIndex" style="width: 100%" :id="'item' + childItem.id"
            @click="toPersonalArticleDetail(childItem.articleId)">
        <view class="item"
              :style="'background-color:'+cardBgColor+';margin:'+margin+'rpx;border-radius:'+radius+'rpx;'">
          <view class="img">
            <base-cover-image :src="childItem.articleCover"/>
          </view>
          <view class="title-info">
            <view class="item-title">{{ childItem.articleTitle }}</view>
            <view class="item-desc" @click.stop="toPersonalIndex(childItem.id, childItem.source)">
              <view class="left">
                <base-cover-image
                    :src="childItem.likePersonImg"
                    :style="{width: '50rpx', height: '50rpx'}"
                />
                <view class="spa">{{ childItem.userName }}</view>
              </view>
              <view class="right" @click.stop="favoriteClick">
                <text class="iconfont icon-aixin"></text>
                <text class="spb">{{childItem.likePerson}}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import {useArticleStore} from '../store'

export default {
  props: {
    //数据源
    dataList: {
      type: Array,
      required: true,
      default: []
    },
    //显示列数
    column: {
      type: Number,
      required: true,
      default: 2
    },
    //卡片margin(rpx)
    margin: {
      type: Number,
      default: 10
    },
    //卡片圆角(rpx)
    radius: {
      type: Number,
      default: 8
    },
    //页面背景颜色
    bgColor: {
      type: String,
      default: '#edeef2'
    },
    //卡片背景颜色
    cardBgColor: {
      type: String,
      default: '#FFFFFF'
    },
  },
  data() {
    return {
      columnData: [],
      columnWidth: 0,
      loading: false,
    };
  },
  watch: {
    dataList: {
      immediate: true,
      deep: true,
      handler(newValue, oldValue) {
        this.$nextTick(() => {
          this.setColumnWidth()
          this.setData()
        })
      },
    },
    column: {
      immediate: false,
      deep: true,
      handler(newValue) {
        this.$nextTick(() => {
          this.setColumnWidth()
          this.setData()
        })
      },
    },
  },
  methods: {
    //计算每列的高度
    getElemHeight(index) {
      this.$nextTick(() => {
        var arr = [];
        this.dataList.map((item, index) => {
          uni.getImageInfo({
            src: item.articleMainPic,
            success: (e) => {
              item.height = (e.height * (this.columnWidth / e.width)) + 'px'
              this.createSelectorQuery().select('#item' + item.id)
                  .boundingClientRect(res => {
                    arr.push({
                      ...{
                        itemHeight: res.height
                      },
                      ...item
                    });
                    if (arr.length == this.dataList.length) {
                      this.columnData = this.distributeToNArrays(arr,
                          this.column);
                    }
                  }).exec();
            }
          })
        })
      })
    },
    distributeToNArrays(arr, n) {
      let sums = new Array(n).fill(0);
      return arr.reduce(
          (arrays, item) => {
            let minSum = Math.min(...sums);
            let minIndex = sums.indexOf(minSum);
            arrays[minIndex].push(item);
            sums[minIndex] += item.itemHeight;
            return arrays;
          },
          new Array(n).fill().map(() => []),
      )
    },
    // 获取机型宽度
    setColumnWidth() {
      // 目前是完整的宽度，如果有padding的需要减去盒子的 padding
      let width = uni.getSystemInfoSync().windowWidth
      this.columnWidth = Math.floor(width / this.column)
    },
    setData() {
      const resultArray = this.dataList.reduce(
          // acc 表示上一次调用回调时的返回值，或者初始值init
          // cur 表示当前正在处理的数组元素
          // index 表示正在处理的数组元素的索引，若提供init值，则索引为0，否则索引为1
          // Array 表示初始值
          (acc, cur, index) => {
            const targetIndex = index % this.column;
            acc[targetIndex].push(cur);
            return acc;
          },
          Array.from(Array(this.column), () => []),
      );
      this.columnData = resultArray
      this.getElemHeight()
    },
    toPersonalArticleDetail(id) {
      // console.log(id, "| id");
      uni.navigateTo({
        url: `/pages/tab-index/personal/article-details/index?id=${id}`,
      })
    },
    // 跳转详情
    toPersonalIndex(id, source) {
      uni.navigateTo({
        url: `/pages/tab-index/personal/index?id=${id}&source=${source}`,
      });
    },
    imageError(e, index, i) {
      console.log(index, "========================");
      // this.officeApp[i]['app_list'][index]['icon'] = '/static/image/other/app-icon.png'
    },
    // 点赞
    favoriteClick() {

    }
  },
};
</script>

<style lang="scss" scoped>
.waterfall {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.column {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.item {
  overflow: hidden;
}

.title-info {
  padding: 0rpx 20rpx 20rpx 20rpx;
}

.item-title {
  font-size: 26rpx;
  color: #333333;
  line-height: 46rpx;
  text-align: justify;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  padding: 15rpx 5rpx;
}

.item-desc {
  font-size: 26rpx;
  color: #666666;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .left {
    display: flex;
    align-items: center;

    .spa {
      margin-left: 15rpx;
      margin-bottom: 22rpx;
      font-size: 20rpx;
    }
  }

  .right {
    display: flex;
    align-items: center;

    .spb {
      font-size: 24rpx;
    }
  }
}
</style>